package com.micai.springboot.controller.admin;

import com.micai.springboot.base.BaseController;
import com.micai.springboot.base.constant.Constants;
import com.micai.springboot.dto.UserDto;
import com.micai.springboot.service.UserService;
import com.micai.springboot.util.MessageUtils;
import com.micai.springboot.vo.UserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 描述：用户管理
 * <p>
 * Author: 赵新国
 * Date: 2017/11/14 15:21
 */
@Controller
@RequestMapping("/admin")
public class AdminLoginController extends BaseController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/toLogin", method = RequestMethod.GET)
    public String toLogin(){
        // 跳转到登录页面
        return "admin/login";
    }

    @RequestMapping(value = "/backLogin", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> pcLogin(UserVo userVo, HttpServletRequest request) {
        Map<String, Object> retMap = null;
        if (!request.getSession().getAttribute(sessionProvider.getSessionId(request)).equals(userVo.getCheckCode())) {
            retMap = MessageUtils.error("验证码输入错误！");
            return retMap;
        }
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userVo.getUserName(), userVo.getPassWord());
        Subject subject = SecurityUtils.getSubject();
        try {
            // 完成登录
            subject.login(usernamePasswordToken);
            UserDto userDto = (UserDto) subject.getPrincipal();
            subject.getSession().setAttribute(Constants.ADMIN_SESSION, userDto);
            // 登录成功，写入当前用户ID到Token
            retMap = MessageUtils.success("登录成功！");
            return retMap;
        } catch (ExcessiveAttemptsException e) {
            retMap = MessageUtils.error("登录失败多次，账户锁定10分钟！");
            return retMap;
        } catch (LockedAccountException lae) {
            usernamePasswordToken.clear();
            retMap = MessageUtils.error("用户已经被锁定不能登录，请与管理员联系！");
            return retMap;
        } catch (AuthenticationException e) {
            usernamePasswordToken.clear();
            retMap = MessageUtils.error("用户或密码不正确！");
            return retMap;
        }
    }

    @RequestMapping("/logout")
    public String logOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/admin/toLogin";
    }

    @RequestMapping("/403")
    public String forbidden(){
        return "error/403";
    }

    //登录
    /*@RequestMapping(value = "/backLogin", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> pcLogin(UserVo userVo, HttpServletRequest request){
        Map<String, Object> retMap = null;
        //1:验证码是否为null
        if(StringUtils.isNotBlank(userVo.getCheckCode())){
            String sessionId = sessionProvider.getSessionId(request);
            if (sessionId.isEmpty()) {
                retMap = MessageUtils.error("回话过期，请重新刷新登录");
                return retMap;
            }
            //2:验证码是否正确
            if(request.getSession().getAttribute(sessionId).equals(userVo.getCheckCode())){
                //3.用户是否为NUll
                if(null != userVo && StringUtils.isNotBlank(userVo.getUserName())){
                    //4:密码是否为NUll
                    if(StringUtils.isNotBlank(userVo.getPassWord())){
                        UserDto userDto = userService.getUserByParam(userVo.getUserName());
                        if(null != userDto){
                            //5.验证密码是否正确
                            if(!userDto.getPassWord().equals(userVo.getPassWord())) {
                                retMap = MessageUtils.error("密码输入错误");
                            } else {
                                //6.验证该用户是否已经分配了权限
                                if (userService.getPermissionCountById(userDto.getId()) > 0) {
                                    //把用户对象 放进Session
                                    sessionProvider.setAttribute(request, Constants.ADMIN_SESSION, userDto);
                                    retMap = MessageUtils.success("登录成功");
                                } else {
                                    retMap = MessageUtils.error("该用户没有分配权限，请联系管理员");
                                }
                            }
                        }else{
                            retMap = MessageUtils.error("用户名输入错误");
                        }
                    }else{
                        retMap = MessageUtils.error("请输入密码");
                    }
                }else{
                    retMap = MessageUtils.error("请输入用户名");
                }
            }else{
                retMap = MessageUtils.error("验证码输入错误");
            }
        }else{
            retMap = MessageUtils.error("请填写验证码");
        }
        return retMap;
    }*/

    /**
     * 后台退出
     * @param request
     * @return
     */
    /*@RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request){
        sessionProvider.logout(request);
        // 重定向到登录页面
        return "redirect:/admin/toLogin";
    }*/

}
